<script setup lang="tsx">
import { AddIcon, SearchIcon } from 'tdesign-icons-vue-next';
import { Link, MessagePlugin, Space } from 'tdesign-vue-next';
import { ref, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { base, modify, addition, del } from '@/api/bank/rechargeRecord';
import MyTable from '@/components/myTable/index.vue';
import OperatingBox from '@/components/operatingBox/index.vue';
import QueryBox from '@/components/queryBox/index.vue';
import { useUserStore } from '@/store/modules/user';
const userStore = useUserStore();
const { t } = useI18n();
const data = ref([]);
const showAddDialog = ref(false);
const addForm = ref({
  bankCode: '',
  bankName: '',
  image: [] as any[],
  imageUrl: '',
});
const onAddClick = () => {
  addForm.value = {
    bankCode: '',
    bankName: '',
    image: [],
    imageUrl: '',
  };
  showAddDialog.value = true;
};
const columns = [
  { title: '银行编号', colKey: 'bankCode' },
  { title: '银行名称', colKey: 'bankName' },
  {
    title: '银行图片',
    colKey: 'image',
    cell: (h: any, { row }: { row: any }) => {
      // 直接展示 row.image 字段（支持字符串或数组）
      let urls: string[] = [];
      if (Array.isArray(row.image)) {
        urls = row.image;
      } else if (typeof row.image === 'string') {
        urls = row.image.split(',').filter(Boolean);
      }
      return (
        <div>
          {urls.map((url) => (
            <img src={url} style="max-width: 80px; max-height: 40px; margin-right: 4px;" />
          ))}
        </div>
      );
    },
  },
  { title: '操作', colKey: 'op' },
];

const pagination = ref({
  defaultCurrent: 1,
  defaultPageSize: 10,
  total: 0,
});

const queryForm = ref({
  uid: '',
  username: '',
  name: '',
  pageNum: 1,
  pageSize: 10,
});

const showEditDialog = ref(false);
const editForm = ref({
  id: '', // 新增原始id字段
  bankCode: '',
  bankName: '',
  image: [] as any[],
  imageUrl: '',
});
const onEditClick = (row: any) => {
  editForm.value.id = row.id;
  editForm.value.bankCode = row.bankCode;
  editForm.value.bankName = row.bankName;

  // 支持多图
  let images = [];
  if (row.image) {
    if (Array.isArray(row.image)) {
      images = row.image;
    } else if (typeof row.image === 'string') {
      images = row.image.split(',').filter(Boolean);
    }
  }
  editForm.value.image = images.map((url: string) => ({ url }));
  editForm.value.imageUrl = images[0] || '';
  showEditDialog.value = true;
};

const onEditConfirm = async () => {
  try {
    // 提交时带上原始id
    const payload = {
      id: editForm.value.id, // 传递原始id
      bankCode: editForm.value.bankCode,
      bankName: editForm.value.bankName,
      image: editForm.value.imageUrl, // 图片路径
    };
    const res = await modify(payload);
    if (res && res.code === 200) {
      MessagePlugin.success('编辑成功');
      showEditDialog.value = false;
      unGetList();
    } else {
      MessagePlugin.error(res?.msg || '编辑失败');
    }
  } catch (e) {
    MessagePlugin.error('编辑请求异常');
  }
};

const onAddConfirm = async () => {
  try {
    const payload = {
      bankCode: addForm.value.bankCode,
      bankName: addForm.value.bankName,
      image: addForm.value.imageUrl,
    };
    const res = await addition(payload);
    if (res && res.code === 200) {
      MessagePlugin.success('新增成功');
      showAddDialog.value = false;
      unGetList();
    } else {
      MessagePlugin.error(res?.msg || '新增失败');
    }
  } catch (e) {
    MessagePlugin.error('新增请求异常');
  }
};

const unGetList = async (isReset = false) => {
  try {
    let params: any;
    if (isReset) {
      params = { pageNum: 1, pageSize: pagination.value.defaultPageSize };
    } else {
      params = {
        dictName: queryForm.value.uid,
        image: queryForm.value.username,
        status: queryForm.value.name,
        pageNum: pagination.value.defaultCurrent,
        pageSize: pagination.value.defaultPageSize,
      };
    }
    const res = await base(params);
    data.value = res.rows;
    pagination.value.total = res.total;
  } catch (e) {
    MessagePlugin.error('查询失败');
  }
};

const onReset = () => {
  queryForm.value = { uid: '', username: '', name: '', pageNum: 1, pageSize: 10 };
  pagination.value.defaultCurrent = 1;
  unGetList(true);
};

onMounted(() => {
  unGetList();
});

async function deleteClickOp(row: any) {
  if (!row.id) {
    MessagePlugin.error('缺少ID，无法删除');
    return;
  }
  try {
    // 可选：弹窗二次确认
    if (window.confirm('确定要删除该银行吗？')) {
      const res = await del(row.id);
      if (res && res.code === 200) {
        MessagePlugin.success('删除成功');
        unGetList();
      } else {
        MessagePlugin.error(res?.msg || '删除失败');
      }
    }
  } catch (e) {
    MessagePlugin.error('删除请求异常');
  }
}

// 上传成功回调，兼容多种后端返回结构，并同步回显
const uploadHeaders = {
  Authorization: `Bearer ${userStore.token}`,
  // 不要手动设置 Content-Type
};

// 定义上传图片的接口地址


const uploadUrl = 'http://192.168.2.35:8080/common/upload';


const uploadImageWithToken = (file) => {
  return new Promise((resolve, reject) => {
    // 检查token是否存在
    if (!userStore.token) {
      reject(new Error('用户未登录，无法上传图片'));
      return;
    }

    const formData = new FormData();
    formData.append('file', file);

    fetch(uploadUrl, {
      method: 'POST',
      body: formData,
      headers: {
        Authorization: `Bearer ${userStore.token}`,
      },
    })
      .then(async (response) => {
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
      })
      .then((data) => {
        if (data.code === 200) {
          // 直接返回后端的图片 url 字段
          resolve(data.url);
        } else {
          reject(new Error(data.msg || '上传失败'));
        }
      })
      .catch((error) => {
        console.error('Upload error:', error);
        reject(error);
      });
  });
};

// 图片上传成功回调
const onImageUploadSuccess = (context) => {
  let url = '';
  if (context?.response?.code === 200) {
    url = context.response.url; // 直接用后端返回的 url 字段
  } else if (context?.file?.url) {
    url = context.file.url;
  }
  editForm.value.imageUrl = url;
  editForm.value.image = [{ url }];
};

// 图片上传成功回调
const onAddImageUploadSuccess = (context) => {
  let url = '';
  if (context?.response?.code === 200) {
    url = context.response.url;
  } else if (context?.file?.url) {
    url = context.file.url;
  }
  addForm.value.imageUrl = url;
  addForm.value.image = [{ url }];
};
</script>

<template>
  <div>
    <OperatingBox>
      <t-button @click="onAddClick">新增</t-button>
    </OperatingBox>
    <QueryBox @reset="onReset" v-model:defaultCurrent="pagination.defaultCurrent" @search="unGetList">
      <t-input v-model="queryForm.uid" placeholder="银行编号" style="width: 240px;">
        <template #prefixIcon>
          <SearchIcon />
        </template>
      </t-input>
      <t-input v-model="queryForm.username" placeholder="银行名称" style="width: 240px;">
        <template #prefixIcon>
          <SearchIcon />
        </template>
      </t-input>
    </QueryBox>
    <MyTable :columns="columns" :data="data" v-model:pagination="pagination" rowKey="bankCode" @unGetList="unGetList">
      <template #op="{ row }">
        <Space>
          <Link theme="primary" @click="onEditClick(row)">修改</Link>
          <Link theme="danger" @click="deleteClickOp(row)">
          {{ t('pages.detailCard.detail.form.delete') }}
          </Link>
        </Space>
      </template>
    </MyTable>
    <!-- 编辑弹窗 -->
    <t-dialog v-model:visible="showEditDialog" header="编辑银行" @confirm="onEditConfirm" @close="showEditDialog = false">
      <t-form>
        <t-form-item label="银行编号">
          <t-input v-model="editForm.bankCode" />
        </t-form-item>
        <t-form-item label="银行名称">
          <t-input v-model="editForm.bankName" />
        </t-form-item>
        <t-form-item label="银行图片">
          <t-upload v-model="editForm.image" theme="image" :max="1" :action="uploadUrl" :show-upload-list="true"
            :auto-upload="true" :headers="uploadHeaders" :on-success="onImageUploadSuccess">
            <t-button>上传图片</t-button>
          </t-upload>

        </t-form-item>
      </t-form>
    </t-dialog>
    <!-- 新增弹窗 -->
    <t-dialog v-model:visible="showAddDialog" header="新增银行" @confirm="onAddConfirm" @close="showAddDialog = false">
      <t-form>
        <t-form-item label="银行编号">
          <t-input v-model="addForm.bankCode" />
        </t-form-item>
        <t-form-item label="银行名称">
          <t-input v-model="addForm.bankName" />
        </t-form-item>
        <t-form-item label="银行图片">
          <t-upload v-model="addForm.image" theme="image" :max="1" :action="uploadUrl" :show-upload-list="true"
            :auto-upload="true" :headers="uploadHeaders" :on-success="onAddImageUploadSuccess">
            <t-button>上传图片</t-button>
          </t-upload>
        </t-form-item>
      </t-form>
    </t-dialog>
  </div>
</template>